package com.extweb4j.core.interceptor;

import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.extweb4j.core.anno.AuthAnno;
import com.extweb4j.core.anno.Log;
import com.extweb4j.core.bean.Msg;
import com.extweb4j.core.comstant.CacheConstant;
import com.extweb4j.core.daoaload.ActionAuthDataLoader;
import com.extweb4j.core.kit.ExtKit;
import com.extweb4j.core.kit.LoginKit;
import com.extweb4j.core.model.ExtLog;
import com.extweb4j.core.model.ExtMenu;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.ehcache.CacheKit;

public class ExtInterceptor implements Interceptor {

	static Logger LOG = Logger.getLogger(ExtInterceptor.class);
	
	static final String NO_AUTH = "您没有权限";
	static final String LOGIN_ERROR = "您的会话已过期,请重新登录";
	
	@Override
	public void intercept(Invocation in) {
		// TODO Auto-generated method stub
		Controller c = in.getController();
		
		// 1.验证权限
		{
			String uid = c.getSessionAttr("uid");
			String action = c.getRequest().getRequestURI();
			
			if(uid==null){
				c.renderJson(new Msg(false, LOGIN_ERROR));
				return;
			}
			
			List<String> auths = new ArrayList<String>();
			List<ExtMenu> list = CacheKit.get(CacheConstant.GLOBAL_CACHE_NAME,(uid+"_action"), new ActionAuthDataLoader(uid));
			for(ExtMenu m : list){
				auths.add(m.getStr("action"));
			}
			
			if(in.getMethod().getAnnotation(AuthAnno.class) != null){
				if(!auths.contains(action)){
					LOG.error(NO_AUTH);
					c.renderJson(new Msg(false, NO_AUTH));
					return;
				}
			}
			
		}
		
		
		// 2.执行Action
		try {
			in.invoke();
			
			//3.记录日志
			Log log = in.getMethod().getAnnotation(Log.class);
			if(log != null){
				 for (Method method : log.annotationType().getDeclaredMethods()) {  
			            if (!method.isAccessible()) {  
			                method.setAccessible(true);  
			            }  
			            Object invoke = method.invoke(log);  
			            String methodName  = method.getName();
			            if(methodName!=null && methodName.equals("value")){
			            	String actionText = invoke.toString();
			            	String userName = LoginKit.getSessionUser(c.getRequest()).getLoginId();
			            	String methodType = c.getRequest().getMethod();
			            	String url = c.getRequest().getRequestURI();
			            	String params  = JsonKit.toJson(c.getRequest().getParameterMap());
			            	new ExtLog()
			            	.set("id", ExtKit.UUID())
			            	.set("user_name", userName)
			            	.set("action_text", actionText)
			            	.set("method", methodType)
			            	.set("log_url", url)
			            	.set("log_params",params)
			            	.set("create_time", new Timestamp(new Date().getTime()))
			            	.save();
			            	LOG.debug("记录日志成功!");
			            }
			        } 
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			c.renderJson(new Msg(false, ExtKit.formatException(e)));
		}
	}

	
}
